Kurt Hsu's blog

The Rails developer in taiwan.


  • 首頁

  • 標籤

  • 分類

  • 歸檔

[CSS]樣式選擇方式

發表於 2016-12-04 更新於 2019-08-20 分類於 CSS

每當CSS樣式越寫越多,越寫越複雜,我們需要有清楚的腦袋知道CSS選擇的是哪些tag,這裡可以參考小資訊。

你可以把CSS看作選擇器

我們跟CSS溝通要選擇P這個原生tag

style.css
1
2
3
4
p {
color: green;
}
代表我選擇P這個Tag讓文字變成綠色的

自創id和class

到後面CSS樣式很多,同一個tag不可能都只用一樣的樣式,這時候id和class自創屬性給他們就相當的實用,而且大多數的時候建議不要擅自改變tag的原生屬性以免將來很難維護。

在html檔案裡面繕寫

index.html
1
2
<div id="green">Yahoo!</div>
<p class="blue">Hello!</p>

在CSS裡像以下為他們冠上屬性

style.css
1
2
3
4
5
6
#green {
color: green;
}
.blue {
color: blue;
}

注意!一個id在body裡面只能使用一次!

逗號(,)為一次選擇多個

style.css
1
2
3
4
5
6
7
h1 {
color: blue;
}

h2 {
color: blue;
}

可以簡寫為

style.css
1
2
3
h1, h2 {
color: blue;
}

選擇一個tag裡的另一個tag

我們可以選擇一個tag裡的幾個tag改變他們的樣式

index.html
1
<div class="content">Hello, my name is <strong class="name">Kurt</strong>, how are you?</div>

此時我只想改變這個content裡的name

style.css
1
2
3
.content .name {
color: blue;
}

選擇擁有該屬性的tag

很多時候tag會加入一些其他的元素,我們也可以利用這個元素來讓CSS選擇到此tag

index.html
1
2
3
<h2 title="index">Hello world</h2>

<h2>Hello world</h2>

我們用利用給他的元素title讓CSS做選擇

style.css
1
2
3
[title] {
color: red;
}

當然也可以指定明確

style.css
1
2
3
[title=index] {
color: red;
}

# CSS
[Angular-1]ng-repeat
[CSS]Box model基礎知識
  • 文章目錄
  • 本站概要

Kurt Hsu

Progress One Percent Every Day
171 文章
55 分類
163 標籤
RSS
  1. 1. 你可以把CSS看作選擇器
    1. 1.1. 自創id和class
    2. 1.2. 逗號(,)為一次選擇多個
    3. 1.3. 選擇一個tag裡的另一個tag
    4. 1.4. 選擇擁有該屬性的tag
© 2020 Kurt Hsu
由 Hexo 強力驅動 v3.8.0
|
主題 – NexT.Muse v7.3.0